<?php

namespace App\Admin\Controllers;

use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use \App\Models\Merchant;
use \App\Models\Floor;
use \App\Models\MerchantCategory;
use App\Admin\Actions\MerchantAction\MerchantSetPassword;
use Encore\Admin\Facades\Admin;

class MerchantsController extends AdminController
{
    protected $title = '商户管理';
    
    protected function grid()
    {
        $grid = new Grid(new Merchant());

	    $grid->disableExport();
	
	    $grid->column('id', 'ID');
	    $grid->column('logo', '品牌图标')->image('', 50, 50);
	    $grid->column('name', '商户名称');
	    $grid->column('floor_id', '楼层')->display(function () {
            return isset($this->floor) ? "{$this->floor->name}" : '';
        });

       
        $grid->column('house_number', '门牌号');
        $grid->column('merchant_category_id', '分类')->display(function () {
            return isset($this->merchantCategory) ? "{$this->merchantCategory->name}" : '';
        });
        $grid->column('password', '密码设置')->bool();
	    $grid->column('created_at', '创建时间')->display(function () {
		    return $this->created_at->toDatetimeString();
	    });
		
		$this->gridFilter($grid);
		$this->gridActions($grid);
	    $grid->disableRowSelector();

        return $grid;
    }

    protected function gridActions(Grid $grid)
    {
	    $grid->actions(function (Grid\Displayers\Actions $actions) {
	    	$actions->disableDelete();

	    	if (in_array(Admin::user()->id, [1,2])) {
		    	$actions->add(new MerchantSetPassword());

 			}
		    
	    });
    }

    protected function gridFilter(Grid $grid)
    {
	    $grid->filter(function (Grid\Filter $filter) {
		    $filter->expand();

		    $filter->column(1/2, function (Grid\Filter $filter) {
		    	$filter->disableIdFilter();
			    $filter->equal('id', '商户名称');
			    $filter->like('name', '商户名称查询');
			   

		    });

		    $filter->column(1/2, function (Grid\Filter $filter) {
			     $filter->equal('floor_id', '楼层查询')->select(Floor::query()->get()->pluck('name', 'id'));
			     $filter->equal('merchant_category_id', '分类查询')->select(MerchantCategory::query()->get()->pluck('name', 'id'));
		    });

	    });
    }
	
	 protected function detail($id)
    {
        $show = new Show(Merchant::findOrFail($id));
        return $show;
    }
	
    protected function form()
    {
        $form = new Form(new Merchant());

        $form->image('logo', '品牌图标')->uniqueName()->removable();
	    $form->text('name', '商户名称');
	    $form->select('floor_id','楼层')->options(Floor::query()->get()->pluck('name', 'id'));
	    $form->text('house_number', '商户门牌号');
	    $form->select('merchant_category_id','分类')->options(MerchantCategory::query()->get()->pluck('name', 'id'));
	    $form->textarea('desc', '商户介绍');
        return $form;
    }
}
